package com.ccteam.fluidmusic.ui.playlist.select

import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.addCallback
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResult
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.FragmentAddOnlineMediaBinding
import com.ccteam.fluidmusic.ui.search.SearchAlbumResultFragment
import com.ccteam.fluidmusic.ui.search.SearchMusicResultFragment
import com.ccteam.fluidmusic.ui.search.SearchPlaylistResultFragment
import com.ccteam.fluidmusic.utils.hideKeyboard
import com.ccteam.fluidmusic.view.bean.LoadMessage
import com.google.android.material.chip.Chip
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author Xiaoc
 * @since 2021/3/17
 *
 * 添加歌曲到歌单的界面Fragment
 */
@AndroidEntryPoint
class AddOnlineMediaFragment: Fragment() {

    companion object{
        /**
         * 当前类型为添加音乐到播放列表
         */
        const val TYPE_ADD_MUSIC_PLAYLIST = 1

        /**
         * 当前类型为添加分享内容到朋友圈
         */
        const val TYPE_ADD_MEDIA_MOMENTS = 2

        /**
         * 当前类型为搜索音乐
         */
        const val TYPE_SEARCH = 3

        /**
         * 当歌单添加完歌曲后，返回时需要告诉上一个Fragment更新当前页面刷新歌单内容
         */
        const val RESULT_PLAYLIST_TYPE_KEY = "playlist_type_result"

        /**
         * 当选择完朋友圈要分享的内容后，返回时需要告诉上一个Fragment选择的内容是什么
         */
        const val RESULT_MOMENTS_TYPE_KEY = "moments_type_result"
    }

    private var _binding: FragmentAddOnlineMediaBinding? = null
    private val binding: FragmentAddOnlineMediaBinding get() = _binding!!

    private val addOnlineMediaViewModel by viewModels<AddOnlineMediaViewModel>()

    private val args by navArgs<AddOnlineMediaFragmentArgs>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        requireActivity().onBackPressedDispatcher.addCallback(this) {
            if(!addOnlineMediaViewModel.selectMusicList.isNullOrEmpty()
                && addOnlineMediaViewModel.type == TYPE_ADD_MUSIC_PLAYLIST
            ){
                    // 告诉上一个Fragment刷新歌单信息
                setFragmentResult(RESULT_PLAYLIST_TYPE_KEY, bundleOf(RESULT_PLAYLIST_TYPE_KEY to true))
            }
            findNavController().navigateUp()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentAddOnlineMediaBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        addOnlineMediaViewModel.loadMessage.observe(viewLifecycleOwner, {
            binding.searchToolbar.isVisible = it is LoadMessage.NotLoading
            binding.statusView.changeToLoadingStatus(it is LoadMessage.Loading)
            binding.statusView.changeToErrorStatus(it)
        })

        addOnlineMediaViewModel.shouldShowResult.observe(viewLifecycleOwner) {
            showHideResult(it)
        }

        binding.searchToolbar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }

        binding.editSearch.setOnFocusChangeListener { _, hasFocus ->
            if(hasFocus){
                addOnlineMediaViewModel.showResult(!hasFocus)
            }
        }

        addOnlineMediaViewModel.searchKey.observe(viewLifecycleOwner, {
            binding.viewpagerSearchResult.adapter = ResultViewPagerAdapter(it)
            TabLayoutMediator(binding.tabSearchResult, binding.viewpagerSearchResult) { tab, position ->
                when(position){
                    0 -> tab.text = getString(R.string.now_playing_tab_music)
                    1 -> tab.text = getString(R.string.online_music_album_type)
                    2 -> tab.text = getString(R.string.online_music_playlistSheet_type)
                }
            }.attach()
        })

        binding.editSearch.setOnKeyListener { _, keyCode, event ->
            if(keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP){
                searchKey(binding.editSearch.text.toString())

                hideKeyboard()
                // 确定搜索内容后，将搜索记录存储到DataStore中
                addOnlineMediaViewModel.editCurrentSearchContent()

                return@setOnKeyListener true
            }
            // 没有进行处理则返回false让Navigation进行回退处理
            return@setOnKeyListener false
        }

        addOnlineMediaViewModel.currentSearchList.observe(viewLifecycleOwner, {
            // 展示最近搜索内容
            updateRecentSearch(it)
        })
    }

    /**
     * 搜索相应内容
     * 会展示搜索结果界面以及清楚聚焦等操作
     */
    private fun searchKey(key: String){
        addOnlineMediaViewModel.showResult(true)
        binding.editSearch.clearFocus()

        addOnlineMediaViewModel.setNewSearchKey(key)
    }

    /**
     * 更新最近搜索的Chip内容
     */
    private fun updateRecentSearch(searchKeys: List<String>) = with(binding){
        chipRecentSearch.removeAllViews()
        searchKeys.forEach {
            val chip = layoutInflater.inflate(R.layout.recent_search_item,
                chipRecentSearch,false) as Chip
            chip.text = it
            chip.isCheckable = false
            // 设置点击事件
            chip.setOnClickListener {
                hideKeyboard()
                searchKey(chip.text.toString())
                binding.editSearch.setText(chip.text.toString())
            }
            binding.chipRecentSearch.addView(chip)
        }
    }

    private fun showHideResult(showResult: Boolean) = with(binding){
//        if(!showResult){
//            editSearch.requestFocus()
//        }
        groupSearchResult.isVisible = showResult
        groupSearchWelcome.isVisible = !showResult
    }

    inner class ResultViewPagerAdapter(private val searchKey: String): FragmentStateAdapter(this){
        override fun getItemCount(): Int {
            return if(args.type == TYPE_ADD_MUSIC_PLAYLIST){
                1
            } else {
                3
            }
        }

        override fun createFragment(position: Int): Fragment {
            if(args.type == TYPE_ADD_MUSIC_PLAYLIST){
                return AddOnlineMusicPagerFragment.newInstance(searchKey)
            }
            return when(position){
                0 -> SearchMusicResultFragment.newInstance(searchKey, TYPE_ADD_MEDIA_MOMENTS)
                1 -> SearchAlbumResultFragment.newInstance(searchKey, TYPE_ADD_MEDIA_MOMENTS)
                2 -> SearchPlaylistResultFragment.newInstance(searchKey, TYPE_ADD_MEDIA_MOMENTS)
                else -> throw IllegalArgumentException("错误的布局参数")
            }

        }

    }

    override fun onDestroyView() {
        super.onDestroyView()

        _binding = null
    }
}